﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HenIT.Data.SqlClient;
using System.Data.SqlClient;
using System.Data;

namespace EventScavenger
{
	internal class EventScavengerDAL : GenericSQLServerDAL
	{
        private SqlConnection insertConn;

		public MachineLogEntry GetMachineLogEntry(string machine, string logName)
		{
			MachineLogEntry machineLogEntry = new MachineLogEntry(machine, logName);
			string sql = "SelectMachineLogEntry";
			try
			{
				SqlParameter[] parameters = new SqlParameter[] 
				{
					new SqlParameter("@Machine", machineLogEntry.Machine),
					new SqlParameter("@LogName", machineLogEntry.LogName),
				};
				DataSet mleds = GetDataSet(sql, CommandType.StoredProcedure, parameters);
				if (mleds.Tables.Count > 0 && mleds.Tables[0].Rows.Count > 0)
				{
					DataRow r = mleds.Tables[0].Rows[0];
					machineLogEntry = new MachineLogEntry(machine, logName);
					machineLogEntry.MachineLogID = (int)r["MachineLogID"];
					machineLogEntry.CollectorId = (int)r["CollectorID"];
					machineLogEntry.Collector = r["Collector"].ToString();
					machineLogEntry.Enabled = (bool)r["Enabled"];
					machineLogEntry.PollFrequency = (int)r["PollFrequency"];
					machineLogEntry.MaxEntryCount = (int)r["MaxEntryCount"];
					machineLogEntry.LastPollTime = (r["LastPollTime"] == DBNull.Value ? new DateTime(2000, 1, 1) : (DateTime)r["LastPollTime"]);
					if (r["PollFilterID"] != DBNull.Value)
					{
						machineLogEntry.PollFilterID = (int)r["PollFilterID"];
						machineLogEntry.PollingFilterName = r["PollingFilterName"].ToString();
						if (r["PollFilterLastChanged"] != DBNull.Value)
						{
							machineLogEntry.PollFilterLastChanged = (DateTime)r["PollFilterLastChanged"];
						}
					}
					try
					{
						machineLogEntry.DBImportEnabled = (bool)r["DBImportEnabled"];
						machineLogEntry.DBImportServer = N(r["DBImportServer"]);
						machineLogEntry.DBImportDatabase = N(r["DBImportDatabase"]);
					}
					catch { }
				}
				else
				{
					machineLogEntry.MachineLogID = -1;
					machineLogEntry.Enabled = false;
				}
			}
			catch (Exception ex)
			{
				lastError = ex.ToString();
			}
			return machineLogEntry;
		}
        public void SetLastMachineLogPollingTime(MachineLogEntry mle, DateTime lastPollTime)
        {
            string sql = "SetLastPollTimeForMachineLog";
            try
            {
                SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@Machine", mle.Machine),
					new SqlParameter("@LogName", mle.LogName),
					new SqlParameter("@LastPollTime", lastPollTime.AddSeconds(-3)) //Allow grace period of 3 seconds to avoid events being missed
				};
                base.ExecuteSP(sql, parms);
            }
            catch { throw; }
            finally
            {

            }
        }

        public string InsertEventLogEntries(System.IO.Stream xml)
        {
            string infoResult = "";
            #region Connection reset
            try
            {
                if (insertConn == null || insertConn.State != ConnectionState.Open)
                {
                    insertConn = null;
                    insertConn = new SqlConnection(connectionString);
                    insertConn.Open();
                }
            }
            catch { throw; }
            finally
            {
            }
            #endregion

            string sql = "InsertEventLogEntries";
            System.Data.SqlTypes.SqlXml sxl = new System.Data.SqlTypes.SqlXml(xml);
            SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@xml", SqlDbType.Xml) { Value = sxl}
				};
            using (SqlCommand cmnd = new SqlCommand(sql, insertConn))
            {
                cmnd.CommandType = CommandType.StoredProcedure;
                cmnd.CommandTimeout = CommandTimeout;
                cmnd.Parameters.AddRange(parms);
                try
                {
                    using (SqlDataReader r = cmnd.ExecuteReader())
                    {
                        if (r.Read())
                        {
                            int duplicates = (int)r["Duplicates"];
                            int repeats = (int)r["Repeats"];
                            int inserts = (int)r["Inserts"];
                            if (duplicates > 1 || repeats > 0)
                            {
                                infoResult = string.Format("{0} inserts, {1} duplicates, {2} repeats, {3} failures, " +
                            "{4}ms duration, last err: {5}",
                                r["Inserts"],
                                r["Duplicates"],
                                r["Repeats"],
                                r["InsertFailures"],
                                r["MSDuration"],
                                r["LastErrorMsg"]);
                            }
                            DoRaiseDBAccessInsertsEvent(inserts);
                        }
                    }

                }
                catch { throw; }
                finally
                {
                }
            }
            return infoResult;
        }

        #region Null handling
        private int I2Null(object value, int defaultValue = 0)
        {
            if (value == null || value == System.DBNull.Value)
                return defaultValue;
            else if (value is int)
                return (int)value;
            else
                return defaultValue;
        }
        private string N(object anyVal)
        {
            if (anyVal == null)
                return "";
            else
                return anyVal.ToString();
        }
        #endregion
	}
}
